<template>
     <div  class="m-window">
        <div class="returnedMoney-col">
            <el-row :gutter="10" style="margin:8px auto;">
                <el-col :span="2">
                    <el-button type="primary" @click="returnAgo" >返回</el-button>
                </el-col>
            </el-row>
            <el-row :gutter="10" style="margin:8px auto;" class="footer-btns-col">
                <el-col :span="2" v-show="pageSourceCode != 'myProcessed'">
                    <el-button type="primary" @click="accomplish">通过</el-button>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <table class="emphasis-table" >
                        <tr prop="itemNo">
                            <th>流程编号：</th>
                            <td><a href="javascript:;" class="hit">{{moneyRowData.itemNo}}</a></td>
                        </tr>
                        <tr>
                            <th>供应商名称：</th>
                            <td>{{moneyRowData.custName}}</td>
                        </tr>
                        <tr>
                            <th>融资金额：</th>
                            <td>{{getFormatActAmt}}元</td>
                        </tr>
                        <tr>
                            <th>融资产品：</th>
                            <td>{{finType}}</td>
                        </tr>
                        <tr>
                            <th>融资到期日期：</th>
                            <td>{{moneyRowData.paybackDate}}</td>
                        </tr>
                    </table>
               </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <div class="detail-headerd">
                        <label>还款明细</label>
                        <div class="opts-col" v-show="pageSourceCode != 'myProcessed'">
                            <a href="javasript:;" class="hit" style="margin-right:18px;" @click="addReturnMoney">添加</a>
                            <a  class="hit shan" @click="deleteshan">删除</a>
                        </div>                        
                    </div>
                </el-col>
            </el-row>
            <ag-grid-vue
                    class="m-agTableContent ag-theme-balham aaa"
                    :gridOptions="applyGridOptions"
                    :columnDefs="applyColumnDefs"
                    :rowData="detailData"
                    v-loading="loading"
                ></ag-grid-vue>
            <el-row>
                <el-col :span="12">
                    <div class="detail-headerd">
                        <label>合计金额：{{totalPayback}}元</label>                  
                    </div>
                </el-col>
            </el-row>
            
        </div>
         <!-- 添加还款记录 模态框-->
        <el-dialog title="添加还款记录" :visible.sync="addReturnMoneyModel" v-dialogDrag :close-on-click-modal="false">            
            <el-form label-width="100px" :model="returnMoneyAddForm" ref="returnMoneyAddForm" :rules="rules">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="还款金额" prop="returnMoney">
                            <el-input
                            size="small"
                            v-model.trim="returnMoneyAddForm.returnMoney"
                            @blur="changeMoney"
                            placeholder="请输入还款金额"
                            @keyup.native="clearNoNum()"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="还款日期" prop="returnDate">
                           <el-date-picker 
                           v-model="returnMoneyAddForm.returnDate" 
                           type="date" 
                           placeholder="选择日期"
                          value-format="yyyy-MM-dd HH:mm:ss"
                           />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="还款性质" prop="returnType">
                           <el-select v-model="returnMoneyAddForm.returnType" placeholder="请选择还款类型" value-key="codeCn" clearable>
                                <!-- <el-option v-for="item in returnTypelist" :key="item.codeCn" :label="item.codeCn"  :value="item"></el-option> -->
                                <el-option
                                  v-for="item in returnTypelist"
                                  :key="item.code"
                                  :label="item.codeCn"
                                  :value="item.code">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeModel">取消</el-button>
                <el-button type="primary" @click="submit('returnMoneyAddForm')">保存</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<style lang="less" scoped>
a.hit {
  color: #409eff;
}
.returnedMoney-col .emphasis-table {
  width: 100%;
  margin-top: 10px;
}
.returnedMoney-col .emphasis-table td,
.returnedMoney-col .emphasis-table th {
  border: 1px solid #eee;
  padding: 10px;
  text-align: right;
}
.returnedMoney-col .emphasis-table td {
  text-align: left;
}
.returnedMoney-col .emphasis-table tr:nth-child(even) th,
.returnedMoney-col .emphasis-table tr:nth-child(even) td {
  background: #f9fafa;
}
.returnedMoney-col .detail-table {
  width: 100%;
  border: 1px solid #eee;
}
.returnedMoney-col .detail-table td,
.returnedMoney-col .detail-table th {
  border-left: 1px solid #eee;
  text-align: center;
  padding: 10px 0;
}
.returnedMoney-col .detail-headerd {
  padding: 10px 0;
}
.returnedMoney-col .detail-headerd .opts-col {
  float: right;
}
.aaa {
  background: #fff;
  width: 50%;
  height: 200px;
  font-size: 14px;
}
  .footer-btns-col,.header-btns-col{
        position:fixed;
        height: 60px;
        width: 100%;
        bottom: 0;
        z-index: 10;
        margin-left: -11px !important;
        box-sizing:border-box;
        display: flex;
        justify-content: center;
        align-items:center;
        background: #fff;
        padding: 10px 0;
        border-top: 1px solid #eee;
        /deep/ .el-button{
        margin-left: -84px;
        }
    }
    .header-btns-col{
        top: 0;
        justify-content: flex-start;
        border-top: none;
        border-bottom: 1px solid #eee;
        margin-top: 100px;
        /deep/ .el-button{
        margin-left: 8px;
        }
    }
</style>
<script>
import Vue from "vue";
import { mapState,mapGetters,mapActions} from "vuex";
import { showAlert } from "lesso-common/public/utils";
import gridOptions from "lesso-common/public/gridOptions";
import { formatPrice,regainOriginalMoneyFormat } from '@/util/format'
export default {
  props:['pageSourceCode'],
  data() {
    return {
      isMakeLoans: false,
      returnedMoneyFrom: {
        signature: [],
        backReason: ""
      },
      isMakeLoansRequired: true,
      isBackReasonRequired: false,
      loading: false,
      // ag-grid 相关
      applyGridOptions: {},
      applyColumnDefs: [],
      detailData: [],
      moneyRowData: {},   //获取融资表格头部数据信息
      returnMoneyAddForm: {
        returnMoney: "",
        returnDate: "",
        returnType:""
      },
      returnTypelist:[],//还款性质
      addReturnMoneyModel: false,
      rules: {
        returnMoney: [
          { required: true, message: "请输入还款金额", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              let reg = /^[1-9]+(\.\d{2})?$/;
              if (reg.test(value == "")) {
                callback("请输入大于0的数字，可保留2位小数");
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        returnDate: [
          { required: true, message: "选择还款日期", trigger: "change" }
        ],
        returnType: [
          { required: true, message: "请选择还款性质", trigger: "blur" }         
        ]
      },
      applyId:"",  //模拟数据
      totalPayback:"0",  //模拟数据
      finType:""
    }; 
  },
  computed: {
		...mapState({
        supplyChainFinance : state => state.supplyChainFinance
    }),
    getFormatActAmt(){
      return formatPrice(this.moneyRowData.actAmt)
    }
	},
  beforeMount() {
    this.returnTypelist = [{code:'0',codeCn:'按时还款'},{code:'1',codeCn:'部分还款'},{code:'2',codeCn:'提前还款'},{code:'3',codeCn:'逾期还款'},{code:'4',codeCn:'不还款'}]
    this.applyGridOptions = gridOptions();
    this.applyColumnDefs = [
      {
        headerName: "序号",
        field: "xuhao",
        checkboxSelection: true, //是否显示复选框
        headerCheckboxSelection: false, //是否显示全选框
        width: 80,
        valueGetter: "node.id",
        cellRenderer: function(params) {
          if (params.value != undefined) {
            return +params.value + 1;
          }
        }
      },
      {
        headerName: "还款日期",
        field: "paybackDate",
        width:105,
        cellRenderer: function(params) {
          if (params.value != undefined) {
            return params.value.substring(0,10)
          }
        }        
      },
      {
        headerName: "还款金额",
        field: "paybackAmount",
        valueFormatter:params=>{
          return formatPrice(params.value)
        }
      },
      {
        headerName: "还款性质",
        field: "paybackProperty",
        width:90,
        valueFormatter:params=>{
          // return (params.value == 0) ? '按时还款' : '逾期还款'
          let cnCode =''
          switch(params.value){
            case 0:
              cnCode = '按时还款';
              break;
            case 1:
              cnCode = '逾期还款';
              break; 
            case 2:
              cnCode = '集团划拨';
              break; 
          } 
          return cnCode
        }
      }
    ];
    //获取流程列表中的数据
    this.applyId = this.supplyChainFinance.role.ID
    
    this.getDetail();
    this.getMoney();
    
  },
  create() {
    
  },
  methods: {
    ...mapActions(['changeMyProcessedCTCode']),
    changeMoney(){
      this.returnMoneyAddForm.returnMoney = formatPrice(this.returnMoneyAddForm.returnMoney)
    },
    //代办查询回款基本信息
    getMoney() {
      var params = {id:this.applyId};
      this.$http.getMoney(params).then(response => {
          if (response.data.code == 200) {
            this.moneyRowData = response.data.rows;
            this.moneyRowData.paybackDate = this.formatDate(response.data.rows.paybackDate)
            let  finType=this.moneyRowData.finType==0?"天进宝":"月有钱"
            this.finType = finType
          } else {
            this.moneyRowData = {};
          }
        })
        .catch(errror => {
          this.$alert("查询失败，请检查网络！", {
            confirmButtonText: "确定",
            customClass: "alertFailure"
          });
        });
    },
    //代办查询还款明细信息
    getDetail() {
      let params = {applyId: this.applyId};
      this.$http.getDetail(params)
        .then(response => {
          console.log(response)
          this.loading = false;
          if (response.data.code == 200) {
            this.detailData = response.data.rows.tblFinSrmPaybackDetailList;
            this.totalPayback = response.data.rows.totalPayback;
          } else {
            this.detailData = [];
          }
        })
        .catch(errror => {
          this.$alert("查询失败，请检查网络！", {
            confirmButtonText: "确定",
            customClass: "alertFailure"
          });
        });
    },
    //代办删除信息
    getShan(params) {
      this.$http.getShan(params).then(Response => {
          this.loading = false;
          if (Response.data.code == 200) {
            this.shanRowData = Response.data.rows;
          } else {
            this.shanRowData = [];
          }
        })
        .catch(errror => {
          this.$alert("查询失败，请检查网络！", {
            confirmButtonText: "确定",
            customClass: "alertFailure"
          });
        });
    },
    //获取行数据
    getRowData(gridApi){
        try {
          if (
            gridApi &&
            gridApi.focusedCellController &&
            gridApi.focusedCellController.focusedCell &&
            gridApi.focusedCellController.focusedCell.rowIndex >= 0) {
                return gridApi.getDisplayedRowAtIndex(gridApi.focusedCellController.focusedCell.rowIndex).data;
            } else {
                return null;
            }
            } catch (error) {
                return null;
            }
    },
    //删除按钮
    deleteshan() {
        // let rowData = this.getRowData(this.applyGridOptions.api);   //获取当前行的数据
        let selectRow = this.applyGridOptions.api.getSelectedRows();   //获取当前行选中的所有行的数据
        if(selectRow<=0){
          this.$alert("请选择要删除的数据！", {
            confirmButtonText: "确定",
            customClass: "alertFailure"
          });
          return false;
        }
        let params=selectRow;
        var _this=this;
        this.$confirm("是否确认删除该数据", "消息提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消"
            }).then(() => {
               _this.$http.getShan(params).then(Response => {
                  _this.loading = false;
                  if (Response.data.code == 200) {
                    _this.$message({
                        type: "success",
                        message: "删除成功"
                    });
                      _this.applyColumnDefs
                      
                      _this.getDetail();
                  } else {
                    // this.shanRowData = [];
                  }
                  
                })
              .catch(error => {
                this.$alert("查询失败，请检查网络！", {
                  confirmButtonText: "确定",
                  customClass: "alertFailure"
                });
              });
                
          })
          .catch(() => {});
       
    },
    //代办保存信息
    getPreservation(){
        this.$http.getPreservation(params).then((Response)=>{
            this.loading = false
            if(Response.data.code == 200){
                this.preservationRowData = Response.data.rows
                // this.total = Response.data.total;
            }else{
                this.preservationRowData = []
                this.total = 0;
            }
        })
        .catch((errror)=>{
            this.$alert("查询失败，请检查网络！", {
            confirmButtonText: "确定",
            customClass: "alertFailure"
            });
        })
    },
    //保存按钮
    submit(formName) {
        let that = this;
        
        let money = regainOriginalMoneyFormat(this.returnMoneyAddForm.returnMoney)
        /***
         * 判断是否添加金额
         */
        if(money<=0){
          this.$alert("请填写金额！", {
              confirmButtonText: "确定",
              customClass: "alertFailure"
          });
          return false;
        };
        /***
         * 判断是否选择时间
         */
        if( this.returnMoneyAddForm.returnDate==""){
          this.$alert("请选择日期！", {
              confirmButtonText: "确定",
              customClass: "alertFailure"
          });
          return false;
        };
        /**
         * 确定添加还款记录事件
         * params:参数
         * 
         */
        
        let params={
          applyId:this.applyId,
          paybackAmount:money,
          paybackDate:this.returnMoneyAddForm.returnDate,
          paybackProperty:this.returnMoneyAddForm.returnType
        }
        this.$refs[formName].validate((valid)=>{
          if (valid) {
            that.$http.savePayBackDetail(params).then(Response => {
                that.loading = false;
                if (Response.data.code == 200) {
                  that.$message({
                        type: "success",
                        message: "添加成功"
                  });
                   let nowDay = this.$utils.dateFormat("yyyy-MM-dd hh:mm:ss", new Date());
                  that.returnMoneyAddForm={
                    returnMoney:'',
                    returnDate:nowDay,
                    returnType:''
                  };
                  that.getDetail();
                }
            })
            .catch(errror => {
              that.$alert("查询失败，请检查网络！", {
                  confirmButtonText: "确定",
                  customClass: "alertFailure"
              });
            });
              this.addReturnMoneyModel = false;

              
          } else {
            console.log("error submit!!");
            return false;
          }
        });

    },
    //取消按钮
    closeModel() {
      this.addReturnMoneyModel = false;
    },
    //结束还款按钮
    accomplish() {
      /**
       * 金额大于融资金额可以还款，否则不能提交
       */
      this.tapPayback()
    },
    /***
     * 请求还款接口按钮事件
     */
    tapPayback(){
      let params={
        applyId:this.applyId,
        
      }
      let _this=this;
      //修改接口名字
      this.$http.submitPayback(params).then(Response => {
          this.loading = false;
          if (Response.data.code == 200) {
            Response.data.rows.result
            if(Response.data.rows.result=="true"){
              this.$confirm("确认结束还款 ？", "消息提示", {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消"
                }).then(() => {
                  _this.unlockApplyLetter()  
                })
                .catch(() => {});
            }else{
              this.$alert("还款总计小于融资金额，不允许结束还款", {
                confirmButtonText: "确定",
                customClass: "alertFailure"
              });
              return
              // this.$confirm("还款总计小于融资金额，确认要结束还款？", "消息提示", {
              //         confirmButtonText: "确定",
              //         cancelButtonText: "取消"
              //   }).then(() => {
              //        _this.unlockApplyLetter()  
              //   })
              //   .catch(() => {});
            }
          }else{
             showAlert({
                        msg: `${Response.data.info}`,
                        type: 0
                    })
          }
        })
      .catch(error => {
        this.$alert("请求失败，请查询网络！", {
          confirmButtonText: "确定",
          customClass: "alertFailure"
        });
      });
    },
    //解锁对账函流程结束
    unlockApplyLetter(){
      let params={
        applyId:this.applyId,
        finType:this.finType=="月有钱"?"1":"0"
      }
      this.$http.unlockApplyLetter(params).then(res => {
         if(res.data.code==200){
            showAlert({
                  msg: "还款成功!",
                  type: 1
            })
            this.$store.dispatch("changeTOdo",{isMyToDoList:0})
            
         }else{
           showAlert({
                  msg: `${res.data.info}`,
                  type: 0
            })
         }
      })
      .catch(error => {
        this.$alert("请求失败，请查询网络！", {
          confirmButtonText: "确定",
          customClass: "alertFailure"
        });
      });
    },
    //返回按钮
    returnAgo() {
      if(this.pageSourceCode == 'myProcessed'){
        this.changeMyProcessedCTCode('')
      }else{
        this.$store.dispatch("changeTOdo",{isMyToDoList:0})
      }
    },
    //添加按钮
    addReturnMoney() {
      this.addReturnMoneyModel = true;
      let nowDay = this.$utils.dateFormat("yyyy-MM-dd hh:mm:ss", new Date());
      this.returnMoneyAddForm.returnDate = nowDay; //设置默认日期今日
    },
    //时间截止到天
    formatDate(time){
      if(time){
        return time.substring(0,10)
      }else{
        return ''
      }
    },
    //只允许输入两位小数
    clearNoNum(){  
        if(typeof  this.returnMoneyAddForm.returnMoney=='string'){ 
            this.returnMoneyAddForm.returnMoney = this.returnMoneyAddForm.returnMoney.replace(/[^(\d|.)]/g,"");
            this.returnMoneyAddForm.returnMoney = this.returnMoneyAddForm.returnMoney.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的   
            this.returnMoneyAddForm.returnMoney = this.returnMoneyAddForm.returnMoney.replace(".","$#$").replace(/\./g,"").replace("$#$",".");  
            this.returnMoneyAddForm.returnMoney = this.returnMoneyAddForm.returnMoney.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数   
            if(this.returnMoneyAddForm.returnMoney.indexOf(".")< 0 && this.returnMoneyAddForm.returnMoney !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额  
                this.returnMoneyAddForm.returnMoney= parseFloat(this.returnMoneyAddForm.returnMoney);  
            }
        }  
    } 
  },
  components: {
    
  }
};
</script>


